const express = require('express');
const app = express();
const mysql = require('mysql2');
const Blog = require('../services/blogServices');


// 静态私服
const path = require('path');
app.use(express.static(path.resolve(__dirname, "../blogWeb")));
app.listen(80, () => {
    console.log("listen 80");
});




// 连接数据库
const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '123456',
    database: 'blog'
})

// 处理post参数
app.use(express.urlencoded({
    extended: true
}));
// 处理json参数
app.use(express.json())


// 上传图片
app.use("/upload", require("./upload"));



// 用户信息请求
app.get("/admin", (req, res) => {
    let tags_count;
    connection.query("SELECT COUNT(id) FROM tags;", function (err, result) {
        tags_count = result[0]['COUNT(id)']
    })
    connection.query("SELECT * FROM admins;", function (err, result) {
        result.push(tags_count)
        res.send(result);
    })
})


// 主页文章摘要请求
app.get("/abstract", async (req, res) => {
    const result = await Blog.getBlogs();
    res.send(result);
})


app.get("/abstract_tags", (req, res) => {
    connection.query(`SELECT BLOGID,TAGID,tag FROM blogs,tags,blogtags WHERE blogs.id=blogtags.BlogId and
    blogtags.TagId=tags.id;`, function (err, result) {
        res.send(result);
    })
})


// 子页面响应
app.get("/details", async (req, res) => {
    let content;
    const result = await Blog.getBlogs();
    result.forEach(item => {
        if (item.id == req.query.id) {
            content = item.content
        };
    })
    res.send(content)
})



app.get("/article_page", async (req, res) => {
    const result = await Blog.getBlogs({
        attributes: ['id', 'title', 'publishTime']
    });
    res.send(result);
})



// 标签页
app.get("/tags", (req, res) => {
    connection.query(`SELECT BLOGID,TAGID,tag,title,abstract,publishTime FROM blogs,tags,blogtags WHERE blogs.id=blogtags.BlogId and
    blogtags.TagId=tags.id;`, function (err, result) {
        res.send(result);
    })
})


// 分类标签页
app.get("/category_tag", (req, res) => {
    connection.query(`SELECT BLOGID,title,abstract,publishTime,tag FROM blogs,tags,blogtags WHERE blogs.id=blogtags.BlogId and
    blogtags.TagId=tags.id;`, function (err, result) {
        res.send(result);
    })
})


app.get("/archives_date", (req, res) => {
    connection.query(`SELECT BLOGID,title,publishTime FROM blogs,tags,blogtags WHERE blogs.id=blogtags.BlogId and
    blogtags.TagId=tags.id;`, function (err, result) {
        res.send(result);
    })
})




// 添加博客
app.post("/addBlog", async (req, res) => {

    console.log(req.body);
    const result = await Blog.addBlog(req.body);
    res.send(result)
})